<template>
  <div class="app-container">
    <div class="search-section card-section">
      <el-form :inline="true" :model="queryParams" ref="queryForm" size="small" label-width="68px">
        <template v-for="(item, idx) in searchItems">
          <el-form-item v-if="showAllSearch || idx < 3" :key="item.prop" :label="item.label" :prop="item.prop">
            <component :is="item.component" v-model="queryParams[item.prop]" v-bind="item.attrs" @change="item.onChange && item.onChange($event)" />
          </el-form-item>
        </template>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button v-if="searchItems.length > 3" type="text" size="mini" @click="showAllSearch = !showAllSearch">
            <span v-if="!showAllSearch">更多 <i class="el-icon-arrow-down"></i></span>
            <span v-else>收起 <i class="el-icon-arrow-up"></i></span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="billList" v-loading="loading" border stripe style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <!-- <el-table-column label="账单ID" prop="id" align="center" width="80" />
        <el-table-column label="订单ID" prop="orderId" align="center" width="80" /> -->
        <el-table-column label="类型" prop="type" align="center" width="90">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type == 1" type="info">运维费</el-tag>
            <el-tag v-else-if="scope.row.type == 3" type="success">门禁卡</el-tag>
            <el-tag v-else-if="scope.row.type == 4" type="warning">人脸</el-tag>
            <el-tag v-else>-</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="公司" align="center">
          <template slot-scope="scope">
            <span>广州云控电子技术有限公司</span>
          </template>
        </el-table-column>
        <el-table-column label="地址详情" align="center" prop="address" width="300" show-overflow-tooltip />
        <el-table-column label="房东姓名" prop="landlordName" align="center" />
        <el-table-column label="房东电话" prop="landlordPhone" align="center" />
        <el-table-column label="门禁编码" prop="door" align="center" />
        <el-table-column label="安装费" prop="unitPrice" align="center" />
        <el-table-column label="月租费" prop="monthPrice" align="center" />
        <el-table-column label="缴费开始日期" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.startDate ? parseTime(scope.row.startDate, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="缴费截止日期" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.endDate ? parseTime(scope.row.endDate, '{y}-{m}-{d}') : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="余额" prop="balance" align="center" />
        <el-table-column label="备注" prop="remark" align="center" />
        <el-table-column label="是否公安" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isPolice == '1'" type="success">是</el-tag>
            <el-tag v-else-if="scope.row.isPolice == '0'" type="info">否</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="创建时间" prop="createTime" align="right" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button type="text" size="small" icon="el-icon-delete" style="color:#F56C6C" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 隐藏新增/编辑弹窗 -->
    <!--
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" append-to-body>
      <el-form :model="form" :rules="rules" ref="form" label-width="90px">
        ...
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    -->
  <!-- </div> -->
</template>

<script>
import { listBillDetail, addBillDetail, updateBillDetail, delBillDetail, exportBillDetail } from '@/api/door/order'
import { parseTime } from '@/utils/ruoyi'
import { listDept } from '@/api/system/dept'
import { deptTreeSelect } from '@/api/system/user'
import { download } from '@/utils/download'

export default {
  name: 'BillList',
  data() {
    return {
      loading: false,
      billList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        landlordName: null,
        landlordPhone: null,
        door: '',
        type: undefined,
        tradeNo: null,
        orderNo: null
      },
      multipleSelection: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: undefined,
        type: undefined,
        name: '',
        phone: '',
        address: '',
        door: '',
        buyCount: 1,
        unitPrice: 0,
        totalPrice: 0,
        province: undefined,
        city: undefined,
        district: undefined,
        street: undefined,
        village: undefined,
        deptId: undefined,
        projectPrice: undefined,
        payStartDate: '',
        payEndDate: '',
        balance: 0,
        remark: ''
      },
      rules: {
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        buyCount: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }],
        totalPrice: [{ required: true, message: '请输入总价', trigger: 'blur' }]
      },
      // 部门数据
      deptOptions: [],
      // 控制显示全部搜索条件
      showAllSearch: false,
      // 搜索条件项
      searchItems: [
        { label: '姓名', prop: 'landlordName', component: 'el-input', attrs: { placeholder: '请输入姓名', clearable: true } },
        { label: '手机号', prop: 'landlordPhone', component: 'el-input', attrs: { placeholder: '请输入手机号', clearable: true } },
        { label: '门禁编码', prop: 'door', component: 'el-input', attrs: { placeholder: '请输入门禁编码', clearable: true } },
        { label: '三方单号', prop: 'tradeNo', component: 'el-input', attrs: { placeholder: '请输入三方单号', clearable: true } },
        { label: '商户订单', prop: 'orderNo', component: 'el-input', attrs: { placeholder: '请输入商户订单', clearable: true } },
        { label: '类型', prop: 'type', component: 'el-select', attrs: { placeholder: '请选择类型', clearable: true, style: 'width: 120px' }, children: [
          { component: 'el-option', attrs: { label: '运维费', value: 1 } },
          { component: 'el-option', attrs: { label: '门禁卡', value: 3 } },
          { component: 'el-option', attrs: { label: '人脸', value: 4 } }
        ] }
      ]
    }
  },
  methods: {
    parseTime,
    getList() {
      this.loading = true
      listBillDetail(this.queryParams).then(res => {
        this.billList = res.rows || []
        this.total = res.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        landlordName: null,
        landlordPhone: null,
        door: '',
        type: undefined,
        tradeNo: null,
        orderNo: null
      }
      this.handleQuery()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取部门名称
    getDeptName(deptId) {
      if (deptId === undefined || deptId === null || deptId === 0) {
        return '-'
      }
      if (!this.deptOptions || this.deptOptions.length === 0) {
        return deptId
      }
      const dept = this.deptOptions.find(d => d.deptId == deptId)
      return dept ? dept.deptName : deptId
    },
    // 初始化部门数据
    initDeptData() {
      // 获取部门数据
      listDept().then(res => {
        this.deptOptions = res.data || []
      })
    },
    // 导出按钮操作
    handleExport() {
      this.$confirm('确认导出所有账单数据?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$message.loading({
          message: "正在导出数据，请稍候...",
          duration: 0
        });
        // 使用POST方法进行导出
        download('/admin-api/door/detail/export', this.queryParams, `账单数据_${parseTime(new Date(), '{y}{m}{d}')}.xlsx`, 'post');
        this.$message.closeAll();
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除该账单明细吗？', '提示', { type: 'warning' }).then(() => {
        delBillDetail(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    handleBatchDelete() {
      if (!this.multipleSelection.length) return
      const ids = this.multipleSelection.map(item => item.id).join(',')
      this.$confirm('确定要批量删除选中的账单明细吗？', '提示', { type: 'warning' }).then(() => {
        delBillDetail(ids).then(() => {
          this.$message.success('批量删除成功')
          this.getList()
        })
      })
    }
  },
  created() {
    // 处理URL参数 - 从房东管理页面跳转过来时自动过滤
    if (this.$route.query.landlordName) {
      this.queryParams.landlordName = this.$route.query.landlordName
    }
    this.getList()
    this.initDeptData()
  }
}
</script>

<style scoped>
.card-section {
  background: #fff;
  padding: 18px 24px 6px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 18px;
}
/* 搜索区域表单项间距优化 */
.search-section ::v-deep .el-form-item {
  margin-right: 60px;
  margin-bottom: 16px;
}
.search-section ::v-deep .el-form-item:last-child {
  margin-right: 0;
}
</style>
